#include <stdio.h>
#include <stdlib.h>
#include <sthread.h>
#include <block.h>
#include <logrw.h>

#define BLKSIZE 8
#define NUMBLK 12
#define NUMREGS 3

// Fills a block with "number" and "version" on its first two integers 
// positions and then writes it on position "number"
#define WRITEBLK(number, version) (block[0]=(char)number, block[1]=(char)version, logrw_write(lbks,number, (char *)block))
// Reads the block indexed by "number", and prints its first two positions: the "number" 
// and "version" of the block
#define READBLK(number) (logrw_read(lbks, number, block))


void *thread_A(void * _lbks) {
	logrw_struct_t *lbks = (logrw_struct_t *)_lbks;
	int i;

	char *block = (char *)malloc(BLKSIZE);

	WRITEBLK(0,1);
	WRITEBLK(2,1);
	WRITEBLK(1,1);
	WRITEBLK(1,2);
    READBLK(0);
	READBLK(1);
	READBLK(2);
	WRITEBLK(1,3);
	READBLK(1);
	WRITEBLK(1,4);
	READBLK(1);
	WRITEBLK(0,2);
	WRITEBLK(2,2);
	WRITEBLK(0,3);
	WRITEBLK(2,3);
	WRITEBLK(0,4);
	WRITEBLK(2,4);

	READBLK(0);
	READBLK(1);
	READBLK(2);

	sthread_exit(NULL);
	return NULL;
}

int main (int argc, const char * argv[]) {
    void *ret;

    sthread_init();
    logrw_struct_t* lbks= logrw_init(NUMREGS, NUMBLK, BLKSIZE);
    sthread_t tA = sthread_create(thread_A, lbks, 1,1,0);
    if(tA == NULL){
	 printf("thread creation failed\n");
	 exit(-1);
	 }
	sthread_join(tA, &ret);
    logrw_free(lbks);
    return 0;
}

